import React, { useState, useEffect, useRef } from "react";
import { Spin, message, Button } from "antd";
import { ListTable, ListColumn } from "@visactor/react-vtable";
import { ExportOutlined } from "@ant-design/icons";
import { downloadExcel, exportVTableToExcel } from "@visactor/vtable-export";
import * as VTable from "@visactor/vtable";
import {getCrmRecordFromSqlMoreLimit} from "../../util/util";

const ZOHO = window.ZOHO;




//报关单明细批量操作
const App = () => {
  const [loading, setLoading] = useState(false);
  const [records, setRecords] = useState(null);
  const tableInstance = useRef(null);
  const [messageApi, contextHolder] = message.useMessage();



  useEffect(() => {
    ZOHO.CRM.UI.Resize({ height: "2000", width: "2000" }).then({});
    fetchData();
  }, []);
  
  const fetchData = async () => {
    try {
        setLoading(true);
        var Entity = window.wdata?.Entity;
        var EntityId = window.wdata?.EntityId;
        
        console.log("Entity",Entity );
        console.log("EntityId",EntityId );

        if(EntityId && EntityId.length > 50){
            message.info("最多只能选择50条数据!");
            setTimeout(async () => {
                await window.ZOHO.CRM.UI.Popup.close();
              }, 1000)
        }else{
            var ids = EntityId.map(id => `'${id}'`).join(',');
            var sql_main = `select Name,Quotationitemname,Companyletterhead.Name as Companyletterhead,Shipper,TotalAmount,Deals.Deal_Name as Deals,Remarks as Remarks_main,field,AccountCode,Account.Account_Name as Account,Accountcontactperson,Owner.first_name as Owner,TransactionMethod,Quotationmethod,Dateofinvoice,Quotationvalidityperiod,Termsandconditions,Paymentterms,ExchangeRate,DestinationPort.Name as DestinationPort,LoadingPort.Name as LoadingPort,Department from Quotations where id in (${ids}) `;
            var sql_detail = `select id,Parent_Id.id as cid,LinkingModule2_Serial_Number as rownum,HSCode,RMB_Opticalplate,USD_Opticalplate,USD_Exportkilogramprice,USD_Finalquotation,USD_Finalquotation_Inversion,ChinesePackagedesp,Productname,Chineseingredients,Chptrequirements_material,Chinesespecification,Shelflife,Nuofboxesinpg,Nuofboxeinnerbox,internalcode,Netweight,Profit,ProfitInversion,Processingfee,PackagesNumber,Packaginunit,Packagingfee,Unit,Netweightofinnebox,Brand,Remarks,Exportprice,Product.Product_Name as Product,Bigbag,AccountprtNo,Smallpackage,Costfee,Sterilizationfee,Quantityperbox,Grossweight,Carton,Englishname,Specification,Minimumorder,Lengthofouterbox,Cartonwidth,Heightofouterbox,Volume from Quotation_PDetails where Parent_Id.id in (${ids}) order by id,LinkingModule2_Serial_Number desc`;
            var result_main = await getCrmRecordFromSqlMoreLimit(sql_main);
            var result_detail = await getCrmRecordFromSqlMoreLimit(sql_detail);

            const mergedData = result_detail.map(detailItem => {
                const mainItem = result_main.find(main => main.id === detailItem.cid);
                
                if (mainItem) {
                    return {
                        ...detailItem,  // 细节数据属性
                        ...mainItem  // 将主数据的所有属性合并到结果对象中
                    };
                } else {
                    return detailItem;
                }
            });
            console.log('mergedData',mergedData);
            if (mergedData) {
                setRecords(mergedData);
            }
        }
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };

  const ready = (instance, isInitial) => {
    if (isInitial) {
      tableInstance.current = instance;
    }
  };


  const option = {
    columns: [
        { field: "Name", title: "报价编号", width: "auto" },
        { field: "rownum", title: "行号", width: "auto" },
        { field: "Quotationitemname", title: "报价项目名称", width: "auto" },
        { field: "Companyletterhead", title: "发货人代码", width: "auto" },
        { field: "Shipper", title: "发货人名称", width: "auto" },
        { field: "TotalAmount", title: "合计金额", width: "auto" },
        { field: "Deals", title: "商机", width: "auto" },
        { field: "Remarks_main", title: "报价备注", width: "auto" },
        { field: "field", title: "审批状态", width: "auto" },
        { field: "Account", title: "客户简称", width: "auto" },
        { field: "Accountcontactperson", title: "客户联系人", width: "auto" },
        { field: "Owner", title: "对外报价所有者", width: "auto" },
        { field: "TransactionMethod", title: "成交方式", width: "auto" },
        { field: "Quotationmethod", title: "报价方式", width: "auto" },
        { field: "Dateofinvoice", title: "报价日期", width: "auto" },
        { field: "Quotationvalidityperiod", title: "报价有效期", width: "auto" },
        { field: "Termsandconditions", title: "条款", width: "auto" },
        { field: "Paymentterms", title: "条款内容", width: "auto" },
        { field: "ExchangeRate", title: "汇 率", width: "auto" },
        { field: "DestinationPort", title: "目的港", width: "auto" },
        { field: "LoadingPort", title: "装运港", width: "auto" },
        { field: "Department", title: "部门", width: "auto" },
        { field: "former_price", title: "former price", width: "auto" },
        { field: "HSCode", title: "HSCode", width: "auto" },
        { field: "RMB_Opticalplate", title: "RMB光板", width: "auto" },
        { field: "USD_Opticalplate", title: "USD 光板", width: "auto" },
        { field: "USD_Exportkilogramprice", title: "USD外销公斤价", width: "auto" },
        { field: "USD_Finalquotation", title: "USD最终报价", width: "auto" },
        { field: "USD_Finalquotation_Inversion", title: "USD最终报价（输入后计算利润）", width: "auto" },
        { field: "ChinesePackagedesp", title: "中文包装描述", width: "auto" },
        { field: "Productname", title: "中文品名", width: "auto" },
        { field: "Chineseingredients", title: "中文成份", width: "auto" },
        { field: "Chptrequirements_material", title: "中文生产要求(材质)", width: "auto" },
        { field: "Chinesespecification", title: "中文规格", width: "auto" },
        { field: "Shelflife", title: "保质期", width: "auto" },
        { field: "Nuofboxesinpg", title: "入数", width: "auto" },
        { field: "Nuofboxeinnerbox", title: "内盒数", width: "auto" },
        { field: "internalcode", title: "内部货号", width: "auto" },
        { field: "Netweight", title: "净重(KG)", width: "auto" },
        { field: "Profit", title: "利润", width: "auto" },
        { field: "ProfitInversion", title: "利润倒算", width: "auto" },
        { field: "Processingfee", title: "加工费", width: "auto" },
        { field: "PackagesNumber", title: "包装包数", width: "auto" },
        { field: "Packaginunit", title: "包装单位", width: "auto" },
        { field: "Packagingfee", title: "包装费", width: "auto" },
        { field: "Unit", title: "单位", width: "auto" },
        { field: "Netweightofinnebox", title: "单净重(G)", width: "auto" },
        { field: "Brand", title: "品牌", width: "auto" },
        { field: "Remarks", title: "商品备注", width: "auto" },
        { field: "Exportprice", title: "商品库外销价格G", width: "auto" },
        { field: "Product", title: "商品编码", width: "auto" },
        { field: "Bigbag", title: "大包+", width: "auto" },
        { field: "AccountprtNo", title: "客户货号", width: "auto" },
        { field: "Smallpackage", title: "小包+", width: "auto" },
        { field: "Costfee", title: "成本费", width: "auto" },
        { field: "Sterilizationfee", title: "杀菌费", width: "auto" },
        { field: "Quantityperbox", title: "每箱数量", width: "auto" },
        { field: "Grossweight", title: "毛重(KG)", width: "auto" },
        { field: "Carton", title: "纸箱", width: "auto" },
        { field: "Englishname", title: "英文品名", width: "auto" },
        { field: "Specification", title: "英文规格", width: "auto" },
        { field: "Minimumorder", title: "起订量", width: "auto" },
        { field: "Lengthofouterbox", title: "长CM", width: "auto" },
        { field: "Cartonwidth", title: "宽CM", width: "auto" },
        { field: "Heightofouterbox", title: "高CM", width: "auto" },
        { field: "Volume", title: "体积CBM", width: "auto" }
    ],
  };




  const handleExport = async () => {

    if (tableInstance.current) {
      downloadExcel(await exportVTableToExcel(tableInstance.current), `报价单导出-${Date.now()}`);
    } else {
      messageApi.info("没有数据可以导出！");
    }
  };

  

  return (
    <div>
      {contextHolder}
      <Spin spinning={loading}>
        <div
          style={{
            display: "flex",
            justifyContent: "flex-end",
            gap: "10px",
            position: "fixed",
            top: 10,
            right: 10,
            zIndex: 9999,
          }}
        >
          <Button
            type="primary"
            shape="circle"
            icon={<ExportOutlined />}
            onClick={handleExport}
          />
        </div>
        <div style={{ paddingTop: "50px" }}>
          <ListTable
            records={records}
            height={"500px"}
            widthMode="standard"
            theme={VTable.themes.DEFAULT}
            dragHeaderMode="column"
            onReady={ready}
            emptyTip= {{text: 'no data records'}}
            rowSeriesNumber = {{title: '序号',width: 'auto'}}
            // frozenColCount={1}
          >
            {option.columns.map((column) => (
              <ListColumn
                key={column.field}
                field={column.field}
                title={column.title}
                width={column.width}
                // editor={column.editor}
                // disableSelect={column.disableSelect}
                // aggregation={column.aggregation}
              />
            ))}
          </ListTable>
        </div>
      </Spin>
    </div>
  );
};

export default App;
